const Type = require("../model/type.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Op = seq.Op;

class TypeService {
  async createType(data) {
    return await Type.create(data);
  }
  async removeType(id) {
    return await Type.destroy({ where: { id } });
  }
  async updateType(id, type) {
    const res = await Type.update(type, { where: { id } });
    return res[0] > 0;
  }

  async findType({ id }) {
    const res = await Type.findOne({
      attributes: ["id", "type_name"],
      where: { id },
    });
    return res ? res.dataValues : null;
  }
  async findAllTypeList() {
    const res = await Type.findAll();
    return res;
  }

  async findAllType({ pageNum, pageSize, type_name }) {
    const offset = (pageNum - 1) * pageSize;

    const whereOpt = {};
    type_name &&
      Object.assign(whereOpt, {
        type_name: {
          [Op.like]: `%${type_name}%`,
        },
      });

    const { count, rows } = await Type.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      where: whereOpt,
      order: [["createdAt", "DESC"]],
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }
}

module.exports = new TypeService();
